package com.cs.beneficios.web.action;
import com.cs.beneficios.business.entity.BeneficiarioDAO;
import com.cs.beneficios.business.model.BeneficiarioVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.common.util.Utility;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.SQLException;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class VerGrupoFamiliarAction extends Action 
{
  /**
   * This is the main action called from the Struts framework.
   * @param mapping The ActionMapping used to select this instance.
   * @param form The optional ActionForm bean for this request.
   * @param request The HTTP Request we are processing.
   * @param response The HTTP Response we are processing.
   * @return 
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
  {
    ActionMessages messages = new ActionMessages();
    HttpSession session = request.getSession();
    try
    {
      	AccessControl access = new AccessControl();
        access.validateAccess(mapping,request,response);
        session.removeAttribute("cabezas");
        session.removeAttribute("msg");
        session.removeAttribute("bene");
        session.removeAttribute("grupo_familiar_Sisben");
        session.removeAttribute("beneficiarios");
        
        String strOption = "VerGrupo";
        String strCode = (String)request.getParameter("code");
        if(strCode == null)
        {
          strCode = (String)session.getAttribute("code");
        }
        session.setAttribute("code",strCode);
        List beneficiarios = (List)session.getAttribute("beneficiarios");
        Collection cBeneficiario = null;
        BeneficiarioVO beneSelected = null;
        session.removeAttribute("grupo_familiar");
        Object gf_code = session.getAttribute("gf_code");
        if(beneficiarios != null){
            for(int i=0;i< beneficiarios.size();i++)
            {
              beneSelected = (BeneficiarioVO)beneficiarios.get(i);
              if(strCode.equals(beneSelected.getCode().toString()))
              {
                try
                {
                  //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
				  ConnectionFactory cf = new ConnectionFactory();
                  BeneficiarioDAO objBeneDAO = new BeneficiarioDAO(cf);
                  if(gf_code != null)
                  {
                    beneSelected.setGrupoFamiliarCode(new Long((String)gf_code));
                    session.removeAttribute("gf_code");
                  }
                  Collection grupo_familiar = objBeneDAO.getGrupoFamiliar(beneSelected);
                  Collection bene = new LinkedList();
                  bene.add(beneSelected);
                  request.setAttribute("bene",bene);
                  cf.closeConnection(objBeneDAO.getConn());
                  request.setAttribute("beneficiarios",bene);
                  if(grupo_familiar.size() > 0){
                    session.setAttribute("grupo_familiar",grupo_familiar);
                  }else
                  {
                    session.setAttribute("msg","No se encontro el grupo familiar registrado en el SUB..");
                  }
                  
                  
                  // BUSQUEDA EN SISBEN
                  objBeneDAO = new BeneficiarioDAO(cf);
                  BeneficiarioVO objBeneVO = new BeneficiarioVO();
                  BeneficiarioVO objBeneficiarioVO = new BeneficiarioVO();
                  objBeneVO = (BeneficiarioVO)beneficiarios.get(i);
//                  objBeneficiarioVO.setTipoDocumento(objBeneVO.getTipoDocumento());
//                  objBeneficiarioVO.setNumeroDocumento(objBeneVO.getNumeroDocumento());
//                  
                  objBeneficiarioVO.setNumeroDocumento(objBeneVO.getNumeroDocumento());
                  objBeneficiarioVO.setTipoDocumento(Utility.deformatSisbenDocument(objBeneVO.getTipoDocumento()));
                  
                  cBeneficiario = objBeneDAO.findBeneficiarioSisben(objBeneficiarioVO);
                  cf.closeConnection(objBeneDAO.getConn()); 
                  
                  if(cBeneficiario != null && cBeneficiario.size() != 0)
                  {
                    if(cBeneficiario.size() > 0)
                    {
                      List beneSisben = (List)cBeneficiario;
                      objBeneVO = (BeneficiarioVO)beneSisben.get(0);
                      
                      objBeneDAO = new BeneficiarioDAO(cf);
//                      Collection grupo_familiar_Sisben = objBeneDAO.getGrupoFamiliarSisben(objBeneVO.getGrupoFamiliar(),objBeneVO.getHogar());
                      Collection grupo_familiar_Sisben = objBeneDAO.getGrupoFamiliarSisben(objBeneVO.getTipoDocumento(),objBeneVO.getNumeroDocumento());
                      cf.closeConnection(objBeneDAO.getConn()); 
                      if(grupo_familiar_Sisben.size() > 0)
                      {
                        session.setAttribute("grupo_familiar_Sisben",grupo_familiar_Sisben);
                        session.setAttribute("InsertGrupoFamiliar",grupo_familiar_Sisben);
                      }else
                      {
                        request.setAttribute("msgerror1","El beneficiario no tiene el grupo familiar registrado en el SISBEN");
                      }
                    }
                  }else
                  {
                    request.setAttribute("msgerror2","El beneficiario no se encuentra registrado en el SISBEN");
                  }
                    
                 // FIN DEL PROCESO 
                
                }catch(SQLException e)
                {
					System.err.println("/******** TDSUB - cwsub");
					e.printStackTrace();
					System.err.println("TDSUB - cwsub ********/");
                }
                break;
              }
            }
        }else
        {
          try
          {
            //ConnectionFactory cf = new ConnectionFactory("beneficios","beneficios");
			ConnectionFactory cf = new ConnectionFactory();
            BeneficiarioDAO objBeneDAO = new BeneficiarioDAO(cf);
            beneSelected = new BeneficiarioVO();
            beneSelected.setCode(new Long(strCode));
            List beneficiario = (List)objBeneDAO.findBeneficiarioByCriterea(beneSelected,"gf");
            if(beneficiario != null && beneficiario.size() > 0)
            {
                Collection grupo_familiar = objBeneDAO.getGrupoFamiliar((BeneficiarioVO)beneficiario.get(0));
                cf.closeConnection(objBeneDAO.getConn());
                request.setAttribute("beneficiarios",beneficiario);
                session.setAttribute("bene",beneficiario);
                if(grupo_familiar.size() > 0){
                  session.setAttribute("grupo_familiar",grupo_familiar);
                }else
                {
                  session.setAttribute("msg","No se encontro el grupo familiar registrado en el SUB..");
                }  
            }else return mapping.getInputForward();
            
            // BUSQUEDA EN SISBEN
              
            objBeneDAO = new BeneficiarioDAO(cf);
            BeneficiarioVO objBeneVO = new BeneficiarioVO();
            BeneficiarioVO objBeneficiarioVO = new BeneficiarioVO();
            objBeneVO = (BeneficiarioVO) beneficiario.get(0);
            objBeneficiarioVO.setTipoDocumento(objBeneVO.getTipoDocumento());
            objBeneficiarioVO.setNumeroDocumento(objBeneVO.getNumeroDocumento());
//            objBeneficiarioVO.setTipoDocumento(Utility.deformatSisbenDocument(objBeneVO.getTipoDocumento()));
            
            cBeneficiario = objBeneDAO.findBeneficiarioSisben(objBeneficiarioVO);
            cf.closeConnection(objBeneDAO.getConn()); 
            
//            if(cBeneficiario != null && cBeneficiario.size() != 0)
//            {
//              if(cBeneficiario.size() > 0)
//              {
//                List beneSisben = (List)cBeneficiario;
//                objBeneVO = (BeneficiarioVO)beneSisben.get(0);
                
                objBeneDAO = new BeneficiarioDAO(cf);
                Collection grupo_familiar_Sisben = objBeneDAO.getGrupoFamiliarSisben(objBeneficiarioVO.getTipoDocumento(),objBeneficiarioVO.getNumeroDocumento());
                cf.closeConnection(objBeneDAO.getConn()); 
                if(grupo_familiar_Sisben.size() > 0)
                {
                  session.setAttribute("grupo_familiar_Sisben",grupo_familiar_Sisben);
                  session.setAttribute("InsertGrupoFamiliar",grupo_familiar_Sisben);
                }else
                {
                  request.setAttribute("msgerror1","El beneficiario no tiene el grupo familiar registrado en el SISBEN");
                }
//              }
//            }else
//            {
//              request.setAttribute("msgerror2","El beneficiario no se encuentra registrado en el SISBEN");
//            }
              
           // FIN DEL PROCESO 
            
          }catch(SQLException e)
          {
			System.err.println("/******** TDSUB - cwsub");
			e.printStackTrace();
			System.err.println("TDSUB - cwsub ********/");
          }
        }
        
        session.setAttribute("Option",strOption);
        session.setAttribute("CodeBeneSelected",strCode);
    }catch (UserException ue) 
        {
         messages.add("msgWarn",  new ActionMessage("loginForm.message."
                                            + ue.getExceptionVO().getId()));
         saveMessages(request, messages);
      	if(ue.getExceptionVO().getId()==AdministrationUserException.ENDED_SESSION)
        {       
              response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        else if(ue.getExceptionVO().getId()==CommonUserException.NOT_ALLOWED_RESOURCE)
        {
            response.sendRedirect(request.getContextPath()+"/admin/tile/invalidatedResource.jsp");
        }
        else
        {
            return mapping.getInputForward();
        }
    }    
    
    return mapping.findForward("success");
  }
}